package moltencore.network.protocol;

import spark.network.protocol.Base;
import spark.network.Util;

public class JoinGame extends Base {
	public static final int NAME_LENGTH_MAX = 12;

	public static final short TYPE = 0x40;
	private static final byte[] TYPE_BYTES = Util.makeBytes(TYPE);

	private byte bubbleSetId;
	private static final int BUBBLE_SET_ID_OFFSET = Base.SIZE;
	private static final int BUBBLE_SET_ID_LENGTH = Byte.SIZE / 8;

	/**
	 * length of the players name
	 */
	private byte nameLength;
	private static final int NAME_LENGTH_OFFSET = BUBBLE_SET_ID_OFFSET + BUBBLE_SET_ID_LENGTH;
	private static final int NAME_LENGTH_LENGTH = Byte.SIZE / 8;

	/**
	 * nickname with whitch the player logs in
	 */
	private byte[] name;
	private static final int NAME_OFFSET = NAME_LENGTH_OFFSET + NAME_LENGTH_LENGTH;

	private static final int SIZE =
			Base.SIZE +
			BUBBLE_SET_ID_LENGTH +
	        NAME_LENGTH_LENGTH;

	public JoinGame() {
		super(true, TYPE_BYTES);
	}

	public byte getBubbleSetId() {
		return bubbleSetId;
	}

	public void setBubbleSetId(byte bubbleSetId) {
		this.bubbleSetId = bubbleSetId;
	}

	public byte[] getName() {
		return name;
	}

	public void setName(String name) {
		byte[] nameBytes = name.getBytes();
		//set the length of the name to the length of the provided string or to the maximal allowed length if the strings
		//length exceeds the maximum length
		nameLength = (byte)((nameBytes.length > NAME_LENGTH_MAX) ? NAME_LENGTH_MAX : nameBytes.length);

		//write nameLength characters into the name byte array
		this.name = new byte[nameLength];
		System.arraycopy(nameBytes, 0, this.name, 0, nameLength);
	}

	@Override
	public void getBytes(byte[] buffer) {
		super.getBytes(buffer);
		buffer[NAME_LENGTH_OFFSET] = nameLength;
		buffer[BUBBLE_SET_ID_OFFSET] = bubbleSetId;
		if(name != null) {
			Util.arraycopy(name, 0, buffer, NAME_OFFSET, nameLength);
		}
	}

	@Override
	public void fill(byte[] buffer) {
		super.fill(buffer);
		bubbleSetId = buffer[BUBBLE_SET_ID_OFFSET];
		nameLength = buffer[NAME_LENGTH_OFFSET];
		name = new byte[nameLength];
		Util.arraycopy(buffer, NAME_OFFSET, name, 0, nameLength);
	}

	@Override
	public int getSize() {
		return SIZE + nameLength;
	}

	public static JoinGame create(byte[] buffer, long receiveTime) {
		JoinGame packet = new JoinGame();
		packet.fill(buffer);
		packet.setTimeStampReceive(receiveTime);
		return packet;
	}
}
